<template>
  <van-popup
    :style="{ height: '100%' }"
    position="bottom"
    v-model="show"
    @close="onClose"
  >
    <img
      :src="photoUrl"
      ref="image"
      v-if="show"
    />
    <div class="crop-bottom">
      <span @click="show = false">取消</span>
      <span @click="updateAvatar">完成</span>
    </div>
  </van-popup>
</template>

<script>
import Cropper from "cropperjs";
import { updateUserAvatar } from "../../../network/user";
export default {
  name: "EditorAvatar",
  props: ["photoUrl", "info"],
  components: {},
  computed: {},
  data() {
    return {
      show: false
    };
  },
  created() {},
  mounted() {},
  methods: {
    isShow() {
      this.show = true;
      // setTimeout(_ => {
      this.$nextTick(_ => {
        const image = this.$refs.image;
        this.cropper = new Cropper(image, {
          // crop (event) {
          //   console.log(event.detail.x)
          //   console.log(event.detail.y)
          //   console.log(event.detail.width)
          //   console.log(event.detail.height)
          //   console.log(event.detail.rotate)
          //   console.log(event.detail.scaleX)
          //   console.log(event.detail.scaleY)
          // },
          viewMode: 1, // 查看模式
          dragMode: "move", // 拖动模式
          aspectRatio: 1, // 截图比例
          autoCropArea: 1, // 自动区域
          cropBoxMovable: false, // 不允许截图区域移动
          cropBoxResizable: false, // 不允许截图区域缩放
          modal: true, // 显示阴影区域
          background: false, // 关闭背景
          movable: true // 允许移动
        });
      });
      // });
    },
    //获取裁剪的图片
    getCroppedBlob() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(resolve);
      });
    },
    async updateAvatar() {
      const fd = new FormData();
      const blob = await this.getCroppedBlob();
      fd.append("photo", blob);
      this.$toast.loading("保存中~");
      const result = await updateUserAvatar(fd);
      if (result.message === "OK") {
        this.info.photo = URL.createObjectURL(blob);
        this.$toast.success("保存成功");
        this.show = false;
      } else {
        this.$toast.fail("保存失败");
        this.show = false;
      }
    },
    onClose() {
      this.$emit('clearFileValue')
    }
  }
};
</script>

<style scoped lang="stylus" >
@import url('~cropperjs/dist/cropper.css')

/* Ensure the size of the image fit the container perfectly */
img
  display block
  /* This rule is very important, please don't ignore this */
  max-width 100%

.van-popup
  background-color #000

.crop-bottom
  position fixed
  bottom 0
  height 44px
  font-size 16px
  color #fff
  /* background: #000; */
  /* background-color: rgba(0, 0, 0, .6); */
  left 0
  right 0
  display flex
  justify-content space-between
  align-items center
  padding 0 16px
</style>